<template>
  <div class="clearfix">
    <a-upload
      list-type="picture-card"
      :file-list="fileList"
      @change="handleChange"
      :customRequest="selfUpload"
      @preview="handlePreview"
      :remove="removeImg"
      :disabled="disabled"
      accept=".docx, .doc, .xlsx, .xls, .pdf, .jpeg, .png"
    >
      <div v-if="fileList.length < 8">
        <a-icon type="plus" />
        <div class="ant-upload-text">上传</div>
      </div>
    </a-upload>
    <j-modal
      title="预览"
      width="900px"
      :visible="previewVisible"
      :footer="null"
      :fullscreen="true"
      @cancel="handleCancel"
    >
      <img alt="example" style="height: 95%;width:100%" :src="previewImage" />
    </j-modal>
  </div>
</template>

<script>
import { ACCESS_TOKEN, TENANT_ID } from '@/store/mutation-types'
import Vue from 'vue'
import { httpAction, deleteAction } from '@/api/manage'
import { Modal } from 'ant-design-vue'

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
  })
}

export default {
  name: 'imgUpload',
  props: ['fileData', 'isShow', 'saveFile', 'dataURL','disabled'],
  watch: {
    dataURL: {
      handler: function(val) {
        if (val) {
          this.uploadImage(val)
        }
      },
      immediate: true
    },
    fileData: {
      handler(val) {
        // console.log(val,val);
        if (val) {
          this.imgList.push(...val)
          this.setFile(val)
        }
      },
      immediate: true
    }
  },
  data() {
    return {
      previewVisible: false,
      previewImage: '',
      upLoad: `${window._CONFIG['domianURL']}/${this.saveFile}`,
      fileList: [
        // {
        //   uid: '-1',
        //   name: 'xxx.png',
        //   status: 'done',
        //   url: 'http://www.baidu.com/xxx.png',
        // },
      ],
      imgList: [],
      remove: '/common/sjWorkImg/remove'
    }
  },
  computed: {
    //token header
    tokenHeader() {
      let head = { 'X-Access-Token': Vue.ls.get(ACCESS_TOKEN) }
      let tenantid = Vue.ls.get(TENANT_ID)
      if (tenantid) {
        head['tenant-id'] = tenantid
      }
      return head
    }
  },
  methods: {
    removeImg(file) {
      // console.log(file, 'file')
      deleteAction(this.remove, { id: file.uid }).then(res => {})
    },
    setFile(file) {
      file.forEach(item => {
        this.fileList.push({
          uid: item.id,
          name: item.fileName,
          status: 'done',
          url: `${window._CONFIG['domianURL']}/sys/common/static/${item.fileUrl}`
        })
      })
    },
    uploadImage(img) {
      let formData = new FormData()
      formData.append('biz', 'ydImg')
      formData.append('img', img)
      httpAction(this.upLoad, formData, 'post').then(res => {
        if (res.success) {
          let { id, fileUrl, fileName } = res.result[0]
          this.fileList.push({
            uid: id,
            name: fileName,
            status: 'done',
            url: `${window._CONFIG['domianURL']}/sys/common/static/${fileUrl}`
          })
          console.log(this.fileList)
          this.imgList.push(res.result[0])
          this.$emit('returnFile', this.imgList)
        } else {
          this.$message.error(res.message)
        }
      })
    },
    handleCancel() {
      this.previewVisible = false
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    handleChange(info) {
      console.log(222, this.upLoad)
      if (info.file.status === 'removed') {
        this.fileList.pop()
        // console.log(info, 'info')
        this.imgList.splice(
          this.imgList.indexOf(
            this.imgList.find(function(element) {
              return element.id === info.file.uid
            })
          ),
          1
        )

        this.$emit('returnFile', this.imgList)
      } else if (info.file.status === 'error') {
      } else {
      }
    },
    selfUpload({ action, file, onSuccess, onError, onProgress }) {
      const base64 = new Promise(resolve => {
        const fileReader = new FileReader()
        fileReader.readAsDataURL(file)
        fileReader.onload = () => {
          resolve(fileReader.result)
          this.uploadImage(fileReader.result)
        }
      })
    }
    /* 导入 */
  }
}
</script>

<style lang='less' scoped>
/deep/ .ant-modal-body {
  text-align: center;
}

.img-box {
  position: relative;
  float: left;
  width: 104px;
  height: 104px;
  margin: 0 8px 8px 0;
  border: 1px solid #fff;
  border-radius: 5px;
  padding: 8px;
}

.img-box-model {
  position: absolute;
  left: 0;
  top: 0;
  z-index: 1;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  opacity: 0;
  transition: all 0.3s;
  content: ' ';
}

.img-box-model:hover,
.img-box-model:hover .img-box-icon {
  opacity: 1;
}

.img-box-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  z-index: 10;
  color: white;
  white-space: nowrap;
  transform: translate(-50%, -50%);
  opacity: 0;
  transition: all 0.3s;
}

/deep/ .ant-upload-picture-card-wrapper {
  width: calc(100% - 112px) !important;
}

/deep/ .ant-modal-header,
/deep/ .ant-modal-title,
/deep/ .ant-modal-close {
  background: transparent !important;
  color: #13d4d5;
}

/deep/ .ant-btn-primary {
  background-color: transparent !important;
  border-color: #1890ff !important;
}

/deep/ .ant-card {
  background-color: transparent;
  color: white;
}

/deep/ .ant-modal-content {
  background: url(~@/assets/hgxjc/lwdwyj/bg.png) no-repeat;
}
/deep/ .ant-upload-list-picture-card {
  .ant-upload-list-item-actions {
    .anticon-eye-o,
    .anticon-delete {
      font-size: 20px;
    }
  }
}
</style>